package com.laikan.reader.article.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.*;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.AndroidUtils;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookfriend.activity.LoginActivity;
import com.laikan.reader.bookreader.activity.SendCommentActivity;
import com.laikan.reader.bookstore.base.BasicWebViewActivity;
import com.laikan.reader.bookstore.view.ScrollWebView;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.LaikanApplication;
import com.laikan.reader.core.bean.ArticelcollectBean;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.FocusDetailBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.BookFileUtils;
import com.laikan.reader.core.utils.ShareSdkReadBookShare;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;

import static com.laikan.reader.R.id.tv_author_name;

/**
 * Created by Administrator on 2016/10/21.
 */
public class BookFocusDetailActivity extends BasicWebViewActivity {

    private EditText etxt_focusdetail_comment;
    private ImageView iv_focusdetail_collect, iv_focusdetail_share, iv_title_back, iv_title_search, iv_title_share;
    private SimpleDraweeView iv_author_icon;
    private RelativeLayout bottomView, titleView, lk_likelook;
    private TextView tv_title, tv_likelook;

    private String mArticleId;
    private boolean mIsCollect;
    private int showAuthorTitle;
    private boolean mIsAttention;

    @SuppressLint ("JavascriptInterface")
    @Override
    protected void assignViews() {
        super.assignViews();
        initSubclassView();
    }

    private void initSubclassView() {
        int marginBottom = AndroidUtils.dip2px(this, 50.0f);
        showAuthorTitle = AndroidUtils.dip2px(this, 70.0f);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        lp.setMargins(0, marginBottom, 0, marginBottom);
        basicview_swiperefresh.setLayoutParams(lp);

        //初始化底部布局
        bottomView = (RelativeLayout)LayoutInflater.from(this).inflate(R.layout.activity_focusdetail_bottomview, null);
        RelativeLayout.LayoutParams bottomParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, marginBottom);
        bottomParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        bottomView.setLayoutParams(bottomParams);
        webview_basic_root.addView(bottomView);
        etxt_focusdetail_comment = (EditText)findViewById(R.id.etxt_focusdetail_comment);
        iv_focusdetail_collect = (ImageView)findViewById(R.id.iv_focusdetail_collect);
        iv_focusdetail_share = (ImageView)findViewById(R.id.iv_focusdetail_share);
        bottomView.setVisibility(View.GONE);

        //初始化顶部布局
        titleView = (RelativeLayout)LayoutInflater.from(this).inflate(R.layout.focus_detail_title, null);
        RelativeLayout.LayoutParams titleParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, marginBottom);
        titleParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        titleView.setLayoutParams(titleParams);
        webview_basic_root.addView(titleView);
        iv_title_back = (ImageView)findViewById(R.id.iv_title_back);
        iv_author_icon = (SimpleDraweeView)titleView.findViewById(R.id.iv_author_icon);
        tv_title = (TextView)titleView.findViewById(tv_author_name);
        iv_title_share = (ImageView)findViewById(R.id.iv_title_share);
        //        lk_likelook = (RelativeLayout)titleView.findViewById(R.id.lk_likelook);
        //        tv_likelook = (TextView)findViewById(R.id.tv_likelook);
    }

    @Override
    protected void initData() {
        super.initData();
        iv_title_back.setImageDrawable(drawable_back);
        basicview_swiperefresh.setEnabled(false); //文章详情页禁止下拉刷新功能
        if (getIntent() != null && getIntent().getStringExtra("articleId") != null) {
            iv_search.setVisibility(View.GONE);
            mArticleId = getIntent().getStringExtra("articleId");
            KLog.e("BookFocusActivity : httpResponse : " + mArticleId);
            setPageLoadData(null, APIProtocol.laikan_bookfocus_article_detail + mArticleId);
            requestData(mArticleId);
        }else {
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        //        if (SPUtil.getBoolean("refresh_article_detail", false)) {
        //            SPUtil.putBoolean("refresh_article_detail", false);
        //            mIsRefreshWebBiew = true;
        //            initData();
        //        }

        String token = SPUtil.getString("token", "");
        String user_ids = SPUtil.getString("user_id", "");
        basicview_webview.loadUrl("javascript:reviewList('" + token+ "')");
        basicview_webview.loadUrl("javascript:clickAttend('" + user_ids+ "')");

    }

    @Override
    protected void initMainWebView() {
        super.initMainWebView();
        basicview_webview.setWebViewClient(null);
        basicview_webview.setWebViewClient(focusDetailWebViewClient);
    }

    @Override
    protected void setListener() {
        super.setListener();
        iv_focusdetail_collect.setOnClickListener(this);
        iv_focusdetail_share.setOnClickListener(this);
        etxt_focusdetail_comment.setOnClickListener(this);
        iv_title_back.setOnClickListener(this);
        //        lk_likelook.setOnClickListener(this);
        //        iv_title_share.setOnClickListener(this);
        etxt_focusdetail_comment.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    writeComment(mArticleId);
                }
            }
        });
        basicview_webview.setOnScrollChangeListener(new ScrollWebView.OnScrollChangeListener() {
            @Override
            public void onPageEnd(int l, int t, int oldl, int oldt) {

            }

            @Override
            public void onPageTop(int l, int t, int oldl, int oldt) {
                titleView.setVisibility(View.GONE);
            }

            @Override
            public void onScrollChanged(int l, int t, int oldl, int oldt) {

            }

            @Override
            public void onScrollYChanged(int y) {
                if (showAuthorTitle < y) {
                    titleView.setVisibility(View.VISIBLE);
                }else {
                    titleView.setVisibility(View.GONE);
                }
            }
        });



    }

    @Override
    protected void onClickEvent(View view) {
        super.onClickEvent(view);
        switch (view.getId()) {
            case R.id.etxt_focusdetail_comment:
                writeComment(mArticleId);
                break;
            case R.id.iv_focusdetail_collect:
                if (mIsCollect) {
                    delCollect(mArticleId);
                }else {
                    MobclickAgent.onEvent(mContext, "kd-wz-sc");//kd-wz-sc
                    addCollect(mArticleId);
                }
                break;
            case R.id.iv_focusdetail_share:
                MobclickAgent.onEvent(mContext,"kd-wz-fx");//精选-文章-分享
                ShareSdkReadBookShare.shareArticle(mArticleId, null, this);
                break;
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.iv_title_share:
                MobclickAgent.onEvent(mContext,"kd-wz-fx");//精选-文章-分享
                ShareSdkReadBookShare.shareArticle(mArticleId, null, this);
                break;
            //            case R.id.lk_likelook:
            //                if (mIsAttention) {
            //                    delLikeLook(mArticleId);
            //                }else {
            //                    addLikeLook(mArticleId);
            //                }
            //                break;
            default:
                break;
        }
    }

    public void requestData(String articleId) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("shorteId", articleId);
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                KLog.e("BookFocusActivity : httpResponse : " + httpResponse.responseContent);

                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<FocusDetailBean>>() {}.getType();
                try {
                    BaseDataBean<FocusDetailBean> focusDetailBean = gson.fromJson(httpResponse.responseContent, type);
                    if (focusDetailBean != null) {
                        if (null == focusDetailBean.getResult() || !Constants.RESULT_OK.equals(focusDetailBean.getResult())) {
                            ToastMgr.showShortToast(focusDetailBean.getError_msg());
                        }else {
                            KLog.e("focusDetailBean.toString() " + focusDetailBean.toString());
                            setData(focusDetailBean);
                        }
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {

            }

            @Override
            public void onFinish() {
            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_bookfocus_article_url_request);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    private void setData(BaseDataBean<FocusDetailBean> focusDetailBean) {
        if (focusDetailBean.getData().isCollect()) {
            iv_focusdetail_collect.setImageResource(R.drawable.focus_likelook);
            mIsCollect = true;
        }else {
            iv_focusdetail_collect.setImageResource(R.drawable.focus_not_likelook);
            mIsCollect = false;
        }
        //        if (focusDetailBean.getData().isAttentoin()) {
        //            tv_likelook.setText(R.string.likelook_done_text);
        //            mIsAttention = true;
        //        }else {
        //            tv_likelook.setText(R.string.likelook_text);
        //            mIsAttention = false;
        //        }
        //        if (focusDetailBean.getData().getAuthorPic() != null) {
        //            iv_author_icon.setImageURI(Uri.parse(focusDetailBean.getData().getAuthorPic()));
        //        }

        tv_title.setText(focusDetailBean.getData().getTitle());
    }

    public void addCollect(final String articleId) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("objectId", articleId);
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                KLog.e("BookFocusActivity : httpResponse : " + httpResponse.responseContent);
                Gson gson = new Gson();
                Type type = new TypeToken<ArticelcollectBean>() {}.getType();
                ArticelcollectBean result = null;
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (result.getResult() == null || !Constants.RESULT_OK.equals(result.getResult())) {
                            ToastMgr.showShortToast(result.getError_msg());
                        }else {
                            if (Constants.RESULT_OK.equals(result.getResult())) {
                                ToastMgr.showShortToast(R.string.collect_success);
                                iv_focusdetail_collect.setImageResource(R.drawable.focus_likelook);
                                mIsCollect = true;
                                ArticelcollectBean.ArticelCollectData articleDataBean = result.getArticalCollectData();
                                LaiKanEvent laiKanEvent = LaiKanEvent.getInstance();
                                laiKanEvent.setElves(articleDataBean);
                                laiKanEvent.setEventID(LaiKanEvent.EVENT_ID_ADD_COLLECT);
                                LaikanApplication.postEvent(laiKanEvent);
                            }
                        }
                    }else {
                        ToastMgr.showShortToast(R.string.collect_failed);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    ToastMgr.showShortToast(R.string.collect_failed);
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.collect_failed);
            }

            @Override
            public void onFinish() {
            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_add_collect);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    public void delCollect(final String articleId) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("objectId", articleId);
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                KLog.e("BookFocusDetailActivity : httpResponse : " + httpResponse.responseContent);
                try {
                    JSONObject jsonObject = new JSONObject(httpResponse.responseContent);
                    if (Integer.parseInt(Constants.RESULT_OK) == jsonObject.getInt("result")) {
                        ToastMgr.showShortToast(R.string.collect_cancel);
                        iv_focusdetail_collect.setImageResource(R.drawable.focus_not_likelook);
                        mIsCollect = false;
                        LaiKanEvent laiKanEvent = LaiKanEvent.getInstance();
                        laiKanEvent.setEventAction(articleId);
                        laiKanEvent.setEventID(LaiKanEvent.EVENT_ID_CANCLE_COLLECT);
                        LaikanApplication.postEvent(laiKanEvent);
                    }else {
                        ToastMgr.showLongToast(jsonObject.getString("error_msg"));
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    ToastMgr.showShortToast(R.string.collect_cancel_failed);
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.collect_cancel_failed);
            }

            @Override
            public void onFinish() {
            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_cancel_collect);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    private void writeComment(String articleId) {
        if (BookFileUtils.isNoLogin()) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }else {
            // TODO: 2016/11/3 有新接口后需要修改的地方
            Intent intent = new Intent(mContext, SendCommentActivity.class);
            intent.setAction("from_focus_detail");
            if (!TextUtils.isEmpty(articleId)) {
                intent.putExtra("shorteId", articleId);
            }
            startActivity(intent);
        }
    }

    public void addLikeLook(String articleId) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("objectId", articleId);
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                KLog.e("BookFocusActivity : httpResponse : " + httpResponse.responseContent);
                try {
                    JSONObject jsonObject = new JSONObject(httpResponse.responseContent);
                    if (Integer.parseInt(Constants.RESULT_OK) == jsonObject.getInt("result")) {
                        //                        ToastMgr.showShortToast(R.string.likelook_done_text);
                        //                        tv_likelook.setText(R.string.likelook_done_text);
                        mIsAttention = true;
                    }else {
                        ToastMgr.showLongToast(jsonObject.getString("error_msg"));
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    ToastMgr.showShortToast(R.string.collect_failed);
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.collect_failed);
            }

            @Override
            public void onFinish() {
            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_add_attention);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    public void delLikeLook(String articleId) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("objectId", articleId);
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                KLog.e("BookFocusActivity : httpResponse : " + httpResponse.responseContent);
                try {
                    JSONObject jsonObject = new JSONObject(httpResponse.responseContent);
                    if (Integer.parseInt(Constants.RESULT_OK) == jsonObject.getInt("result")) {
                        //                        ToastMgr.showShortToast(R.string.likelook_cancel);
                        //                        tv_likelook.setText(R.string.likelook_text);
                        mIsAttention = false;
                    }else {
                        ToastMgr.showLongToast(jsonObject.getString("error_msg"));
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    ToastMgr.showShortToast(R.string.collect_failed);
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.collect_failed);
            }

            @Override
            public void onFinish() {
            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_cancel_attention);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    private WebChromeClient webChromeClient = new WebChromeClient() {

    };

    private WebViewClient focusDetailWebViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mIsPageLoadingSucess = true;
            if (!mIsRefreshWebBiew) { tipinfo.setLoading(); }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mIsPageLoadingSucess = false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            basicview_swiperefresh.setRefreshing(false);
            dismissDialog();
            if (mIsPageLoadingSucess) {
                tipinfo.setHide();
                bottomView.setVisibility(View.VISIBLE);
            }else {
                tipinfo.setLoadError(R.string.laikan_data_load_failed);
                mIsRefreshWebBiew = false;
            }
            isFinish = true;
        }

        // 接口错误404时 回调
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            if(!isFinish){
                view.loadUrl("");
                mIsPageLoadingSucess = false;
                tipinfo.setLoadErrorNotDelayed(R.string.laikan_network_anomaly);
                mIsRefreshWebBiew = false;

            }
        }
    };
}